<template>
  <div class="app-container">
    <basics-form ref="basicsForm" :minWidth="'300px'" :actionLoading="loading" @actionBtnsClick="actionBtnsClick"
      @selectCallback="selectCallback" @submit="search" />
    <el-table v-loading="tableLoading" ref="multipleTable" :data="tableData" border stripe style="width: 100%"
      @selection-change="(e)=>{multipleSelection =e}">
      <el-table-column type="selection" width="40" v-if="roleId == 4">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="80"> </el-table-column>
      <el-table-column prop="doctorName" label="所属医生" width="100"> </el-table-column>
      <el-table-column prop="telphone" label="手机号" width="110"> </el-table-column>
      <el-table-column prop="age" label="年龄" width="60"> </el-table-column>
      <el-table-column label="性别" width="60">
        <template slot-scope="scope">
          <span>{{
            scope.row.sex == 1 ? "男" : scope.row.sex == 0 ? "女" : "未知"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="diseaseCategory" label="患者病类"  width="110">
      </el-table-column>
      <el-table-column prop="postName" label="设备绑定时间"  width="135">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.bindTime ? '#409EFF' : '' }">
            {{ scope.row.bindTime?scope.row.bindTime.substring(0,16):"未绑定" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="postName" label="上次测量">
        <template slot-scope="scope">
          <div v-if="scope.row.prevTest.testDate" class="test-wrap">
            <div>
              收缩压(mmHg)：<label :style="{
                  color:scope.row.prevTest.isSbpAbnormal ? colors[scope.row.prevTest.sbpAbnormalLevel-1] : '',
                }">{{ scope.row.prevTest.sbp }}</label>
            </div>
            <div>
              舒张压(mmHg)：<label :style="{
                  color: scope.row.prevTest.isDbpAbnormal ? colors[scope.row.prevTest.dbpAbnormalLevel-1] : '',
                }">{{ scope.row.prevTest.dbp }}</label>
            </div>
            <div>
               脉搏(次/分)：<label>{{ scope.row.prevTest.hr }}</label>
            </div>
            <div>
            <label>{{ scope.row.prevTest.testDate.substring(0,16) }}</label>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="postName" label="有无血压报告" width="100">
        <template slot-scope="scope">
          <span :style="{color:scope.row.isHaveDynamicReport?'#409EFF':''}">
           {{scope.row.isHaveDynamicReport?'有':'无'}}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="postName" label="是否待关怀" width="90" v-if="roleId==4">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isNeedCare" size="mini" type="text" icon="el-icon-s-unfold"
            @click="showCare(scope.row)">待关怀</el-button>
          <span v-else>无需关怀</span>
        </template>
      </el-table-column>
      <el-table-column prop="postName" label="是否关注" width="80" v-if="roleId==4">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isFollow" @change="followChange(scope.row.patientId,scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="220px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="showDetails(scope.row)" v-if="roleId==4">修改
          </el-button> -->
          <el-button size="mini" type="text" icon="el-icon-search" @click="showData(scope.row)">测量数据表格</el-button>
          <el-button size="mini" type="text" icon="el-icon-search" @click="showData(scope.row,true)">测量数据趋势图</el-button>
          <el-popconfirm
            style="margin-left: 10px"
            title="确定删除吗？"
            v-if="roleId==3"
            @confirm="del(scope.row.patientId)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="text"
              icon="el-icon-delete"
              >删除</el-button
            >
          </el-popconfirm>
          <el-button size="mini" type="text" v-if="roleId==4" icon="el-icon-warning-outline"
            @click="showTips(scope.row)">患者提醒</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link" v-if="roleId==4">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="xgzl" icon="el-icon-edit">修改资料</el-dropdown-item>
              <el-dropdown-item command="bdsb" icon="el-icon-circle-plus-outline">绑定设备
              </el-dropdown-item>
              <el-dropdown-item command="qywh" icon="el-icon-s-check">亲友维护</el-dropdown-item>
              <el-dropdown-item command="ghys" icon="el-icon-refresh-left" v-if="scope.row.changeState != 0">
                更换医生</el-dropdown-item>
                   <el-dropdown-item command="xyycbz" icon="el-icon-edit">
                血压异常标准</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div v-if="scope.row.changeState > -1" :style="{ color: scope.row.changeState ? '#e83112' : '#1dbc9a' }">
            更换医生{{ scope.row.changeState ? "拒绝" : "审核中" }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="$refs.basicsForm.formValid()" />

    <el-dialog :title="item ? '修改' : '新增'" :visible.sync="openView" width="1200px" append-to-body>
      <el-button  type="primary" style="margin-bottom: 10px;" @click="getMsg">从设备获取信息</el-button>
      <basics-form @selectCallback="selectCallback" ref="basicsAddForm" :minWidth="'400px'" :titleAligin="'right'"
        :titleWidth="'130px'" :actionLoading="loading" @actionBtnsClick="addAction" @submit="addSubmit">
        <template v-slot:inside="{ ruleKey, slotData }">
          <el-button v-if="ruleKey == 'smsCode'" @click="getCode" :disabled="codeWaitTime != 60">
            {{ codeWaitTime == 60 ? "点击获取" : codeWaitTime + "s后重试" }}
          </el-button>
        </template>
      </basics-form>
    </el-dialog>
    <el-dialog title="测量数据" :visible.sync="dataView" width="80vw" append-to-body>
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <el-tab-pane label="表格" name="first">
          <my-table ref="table" :patientName="item?item.name:''"/>
        </el-tab-pane>
        <el-tab-pane label="趋势图" name="second">
          <my-charts ref="charts" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog title="绑定设备" :visible.sync="bindView" width="1100px" append-to-body>
      <my-bind ref="bind" @getList="getList"/>
    </el-dialog>
    <el-dialog title="更换医生" :visible.sync="changeDoctorView" width="700px" append-to-body>
      <basics-form ref="basicsChangeDoctorForm" :titleAligin="'right'" :titleWidth="'130px'" :actionLoading="loading"
        @actionBtnsClick="changeDoctorAction" @submit="changeDoctorSubmit" />
    </el-dialog>
    <el-dialog title="亲友维护" :visible.sync="kithView" width="35vw" append-to-body>
      <my-kith ref="kith" />
    </el-dialog>
    <el-dialog title="待关怀" :visible.sync="careView" width="80vw" append-to-body>
      <my-care ref="care" />
    </el-dialog>
    <el-dialog title="患者提醒" :visible.sync="tipsView" width="80vw" append-to-body>
      <my-tips ref="tips" />
    </el-dialog>
    <el-dialog title="批量发送提醒" :visible.sync="sendView" width="1100px" append-to-body>
      <basics-form style="margin-left: 100px" @selectCallback="selectCallback" ref="basicsSendForm" :minWidth="'800px'"
        :titleAligin="'right'" :titleWidth="'130px'" :actionLoading="loading" @actionBtnsClick="sendAction"
        @submit="sendSubmit" />
    </el-dialog>
    <el-dialog title="单独设置血压异常标准" :visible.sync="standardView" width="700px" append-to-body>
      <basics-form  style="margin-left: 100px" ref="basicsStandardForm" :titleAligin="'right'" :titleWidth="'240px'"
       :actionLoading="loading"
        @actionBtnsClick="standardAction" hiddenMustIcon @submit="standardSubmit" />
    </el-dialog>
    <el-dialog
      :title="'批量导入'"
      :visible.sync="batchImportOpen"
      :width="'700px'"
      append-to-body
    >
      <span
        style="color: rgb(3, 167, 240); cursor: pointer"
        @click="down"
        >点击下载模板</span
      >
      <basics-form
        :style="{ marginLeft:  '100px' }"
        ref="batchImportForm"
        :minWidth="'400px'"
        :titleAligin="'right'"
        :titleWidth="'130px'"
        :actionLoading="loading"
        @actionBtnsClick="batchImportAction"
        @submit="batchImportSubmit"
      />
    </el-dialog>
  </div>
</template>

<script>
  import BasicsForm from "@/components/BasicsForm";
  import {
    patientList,
    doctorAllList,
    savePatient,
    listNationOfWeb,
    listDiseaseCategoryOfWeb,
    discernIdCardOfWeb,
    addPatientOfWeb,
    updatePatientOfWeb,
    sendSmsCodeOfWeb,
    followPatientOfWeb,
    changeDoctorOfWeb,
    removePatient
  } from "@/api/manbing/patient";

  import {
    hospitalAllList,
    provinceList
  } from "@/api/manbing/hospital";
  import {
    remindWordsListOfWeb,
    addRemindBatchOfWeb
  } from "@/api/manbing/message";
  import {
    getBloodStandard,
  saveBloodStandard
  } from "@/api/manbing/hospital";
  import {
    parseTime
    } from "@/utils/ruoyi";
  import myTable from "./table";
  import myCharts from "./charts";
  import myBind from "./bind";
  import myCare from "./care";
  import myTips from "./tips";
  import myKith from "./kith"
  export default {
    name: "Patient-item",
    components: {
      BasicsForm,
      myTable,
      myCharts,
      myBind,
      myCare,
      myTips,
      myKith
    },
    props: {
      watchFlag: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        colors:['#409EFF','rgb(253,154,1)','red'],//警告颜色
        roleId: sessionStorage.getItem("roleId"),
        loading: false,
        tableLoading: false,
        openView: false, //新增医院弹出
        total: 0,
        types: ["所有患者", "今日已测量", "今日未测量", "今日异常", "潜在流失", "累计异常",
              '已绑定设备','未绑定设备','上月新增患者','上月绑定设备','活跃患者'],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          searchType: 0,
          keyWord:''
        },
        tableData: [],
        item: null, //操作的数据
        telphone: '',
        doctors: null,
        hospitals: null,
        hospitalId: '',
        nationList: null, //民族
        diseaseList: null, //病类
        provinces: null, //省市区
        dataView: false, //测量数据弹出
        activeName: "first", //测量数据显示类型
        chartsFlag: false,
        height: 0,
        weight: 0,
        codeWaitTime: 60,
        bindView: false, //绑定设备弹出
        changeDoctorView: false, //更换医生弹出

        careView: false, //待关怀弹出
        tipsView: false, //患者提醒弹出
        sendView: false, //批量提醒弹出
        kithView: false, //亲友维护弹出
        multipleSelection: [], //选中的患者
        remind: null, //常用语

        standardView: false, //血压异常标准弹出
        standard: null, //血压异常标准
        batchImportOpen:false,//导入弹出
      };
    },
    watch: {
      $route(to, from) {
        if(!this.watchFlag){
          return
        }
        console.log(from,'-----');
        if (to.path.indexOf('/manbing/patient') > -1&&(from.path.indexOf('/manbing/screen')>-1 ||from.name=='Index' )) {
          let patientName = this.$route.query.patientName
          if (patientName) {
           this.queryParams.keyWord = patientName
           this.queryParams.searchType =0
          }else{
            this.queryParams.keyWord = ''
            let type = this.$route.query.type
            if (!type || isNaN(type)) {
             type=0
            }
            this.queryParams.searchType = Number(type)
          }
          let index=this.$route.query.index
           if (index!=undefined || isNaN(index)) {
              this.queryParams.diseaseCategory= Number(index)
           }else{
             this.queryParams.diseaseCategory=''
           }
          let today=this.$route.query.today
           if (today) {
              this.queryParams.filingStartDate =parseTime(new Date()).substring(0,10)
              this.queryParams.filingEndDate = parseTime(new Date()).substring(0,10)
           }else {
                this.queryParams.filingStartDate = ''
                this.queryParams.filingEndDate = ''
              }
           this.queryParams.pageNum=1
           this.initRules()
          // this.doctorListDiseaseCategory(false);
        }
      }
    },
    created() {
      if(!this.watchFlag){
        return
      }
        let patientName = this.$route.query.patientName
          if (patientName) {
           this.queryParams.keyWord = patientName
           this.queryParams.searchType =0
          }else{
            let type = this.$route.query.type
            if (!type || isNaN(type)) {
             type=0
            }
            this.queryParams.searchType = Number(type)
          }
          let index=this.$route.query.index
           if (index!=undefined || isNaN(index)) {
              this.queryParams.diseaseCategory= Number(index)
           }else{
             this.queryParams.diseaseCategory=''
           }
           let today=this.$route.query.today
            if (today) {
               this.queryParams.filingStartDate =parseTime(new Date()).substring(0,10)
               this.queryParams.filingEndDate = parseTime(new Date()).substring(0,10)
            }else {
                 this.queryParams.filingStartDate = ''
                 this.queryParams.filingEndDate = ''
               }
        this.$nextTick(() => {
          if(this.roleId != 2){
            this.bloodStandard()
          }
          if (this.roleId == 3) {
            this.getDoctors(false,true);
          } else if (this.roleId == 4) {
            let type = this.$route.query.type
            if (type && !isNaN(type)) {
              this.queryParams.searchType = Number(type)
            }
            this.doctorListDiseaseCategory(false);
          } else {
            this.getHospitals();
          }
        });

    },
    methods: {
      init(patientId,name){
         this.queryParams.keyWord = name
         this.queryParams.searchType =0
         this.$nextTick(() => {
           if(this.roleId != 2){
             this.bloodStandard()
           }
           if (this.roleId == 3) {
             this.getDoctors();
             this.doctorListDiseaseCategory(false);
           } else if (this.roleId == 4) {
             let type = this.$route.query.type
             if (type && !isNaN(type)) {
               this.queryParams.searchType = Number(type)
             }
             this.doctorListDiseaseCategory(false);
           } else {
             this.getHospitals();
           }
         });
      },
      getHospitals() {
        hospitalAllList({}).then((res) => {
          if (res.code == 200) {
            this.hospitals = res.data;
            this.hospitalId= this.hospitals[0].deptId
            this.getDoctors();
            this.doctorListDiseaseCategory(false);
            if(this.roleId == 2){
              this.bloodStandard()
            }
          }
        });
      },
      getDoctors(changeFlag,categoryFlag) {
        if (this.roleId == 4) {
          return;
        }
        if ((this.roleId != 3 && this.hospitals.length) || this.roleId == 3) {
          let data = {};
          if (this.roleId != 3 && this.hospitals.length) {
            data.deptId = this.hospitalId;
          }
          doctorAllList(data).then((res) => {
            if (res.code == 200) {
              this.doctors = res.data;
              if (changeFlag) {
                this.$refs.basicsForm.changeRulesValue([{
                  index: 1,
                  key: "selectList",
                  value: res.data,
                }, ]);
                this.$refs.basicsForm.changeParamValue({
                  key: "doctorId",
                  value: "",
                });
              }
              if(categoryFlag){
                this.doctorListDiseaseCategory(false);
              }
            }
          });
        }
      },

      initRules() {
        let rules = [{
            title: "关键字",
            key: "keyWord",
            placeholder: "ID/姓名/手机号",
            value:this.queryParams.keyWord,
            skip: true,
          },
          {
            title: "类型",
            key: "searchType",
            type: 'select',
            selectList: this.types,
            hiddenClose: true,
            value: this.queryParams.searchType,
            skip: true,
          },
          {
            title: "年龄",
            key: "ageStart",
            rangeKey: "ageEnd",
            type: 'numberRange',
            skip: true,
          },
          {
            title: "病类",
            key: "diseaseCategory",
            type: "select",
            selectList: this.diseaseList||[],
            value:this.queryParams.diseaseCategory,
            skip: true,
          }, {
            title: "性别",
            key: "sex",
            type: "select",
            selectList: [{
              name: '男',
              value: 1
            }, {
              name: '女',
              value: 0
            }],
            selectKey: 'value',
            skip: true,
          }, {
            title: "上次测量时间",
            key: "date",
            type: "daterange",
            selectKey: 'value',
            skip: true,
          },{
            title: "建档时间",
            key: "date2",
            type: "daterange",
            selectKey: 'value',
            value:[this.queryParams.filingStartDate||'', this.queryParams.filingEndDate||''],
            skip: true,
          },
          {
            type: "actionBtns",
            selectList: [{
              name: "搜索",
              value: "primary"
            },{
               name: "导出",
               value: "success"
             }],
            ruleWidth: "auto",
          }
        ];
        if (this.roleId != 4) {
          rules.unshift({
            title: "所属医生",
            key: "doctorId",
            type: "select",
            selectList: this.doctors||[],
            selectKey: "doctorId",
            selectShowKey: "name",
            skip: true,
            value: "",
          });
          if (this.roleId != 3) {
            rules.unshift({
              title: "所属医院",
              key: "deptId",
              type: "select",
              selectList: this.hospitals||[],
              selectKey: "deptId",
              selectShowKey: "deptName",
              skip: true,
              value: 0,
              callback: true,
              hiddenClose: true,
            });

          }
        } else {
          rules[7].selectList.push({
               name: "导入",
               value: "warning"
             })
             rules[7].selectList.push({
            name: "新增",
            value: "success"
          })
          rules[7].selectList.push({
            name: "批量提醒",
            value: "warning"
          })
        }

        this.$refs.basicsForm.initForm(rules);
        this.$nextTick(() => {
          this.$refs.basicsForm.formValid();
        });
      },

      actionBtnsClick(index) {
        if(index==1){

           this.download('/chronicdisease/hospital/patientExport', {
                   ...this.queryParams
                 }, `患者列表_${new Date().getTime()}.xlsx`)
        }else if(index==2){
         this.batchImportOpen=true
         this.$nextTick(()=>{
           this.initImport()
         })
        }else if (index == 3) {
          this.item = null;
          this.openView = true;
          this.$nextTick(() => {
            this.doctorListNation();
          });
        } else if (index == 4) {
          if (this.multipleSelection.length < 1) {
            this.$modal.msgWarning("请选择患者");
          } else {
            this.showSend()
          }
        } else {
          this.queryParams.pageNum = 1;
          this.$refs.basicsForm.formValid();
        }
      },
      //搜索
      search(param) {
        if (!param) {
          return;
        }
        for (let key in param) {
          this.queryParams[key] = param[key];
        }
        this.queryParams.diseaseCategory = this.diseaseList[this.queryParams.diseaseCategory];
        if (this.queryParams.date && this.queryParams.date.length) {
          this.queryParams.startDate = this.queryParams.date[0]
          this.queryParams.endDate = this.queryParams.date[1]
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
        if (this.queryParams.date2 && this.queryParams.date2.length) {
          this.queryParams.filingStartDate = this.queryParams.date2[0]
          this.queryParams.filingEndDate = this.queryParams.date2[1]
        } else {
          this.queryParams.filingStartDate = ''
          this.queryParams.filingEndDate = ''
        }
        delete this.queryParams.date
        delete this.queryParams.date2
        this.getList();
      },

      getList() {
        this.loading = true;
        this.tableLoading = true;
        patientList(this.queryParams)
          .then((res) => {
            if (res.code == 200) {
              this.tableData = res.rows.map((item, ind) => {
                item.isFollow = item.isFollow == 1 ? true : false
                return item;
              })
              this.total = res.total;
            }
          })
          .finally(() => {
            this.loading = false;
            this.tableLoading = false;
          });
      },
      showDetails(item) {
        this.openView = true;
        this.item = item;
        this.$nextTick(() => {
          this.doctorListNation();
        });
      },
      //民族
      doctorListNation(data, disabled) {
        if (this.nationList) {
          this.doctorListDiseaseCategory(true);
        } else {
          listNationOfWeb().then((res) => {
            if (res.code == 200) {
              this.nationList = res.data;
              this.doctorListDiseaseCategory(true);
            }
          });
        }
      },
      //病类
      doctorListDiseaseCategory(flag) {
        if (this.diseaseList) {
          if (flag) {
            this.getProvinces();
          } else {
            this.initRules();
          }
        } else {
          listDiseaseCategoryOfWeb().then((res) => {
            if (res.code == 200) {
              this.diseaseList = res.data;
              if (flag) {
                this.getProvinces();
              } else {
                this.initRules();
              }
            }
          });
        }
      },
      //省市区列表
      getProvinces() {
        if (this.provinces) {
          this.initAddRules();
        } else {
          provinceList().then((res) => {
            if (res.code == 200) {
              this.provinces = res.data;
              this.initAddRules();
            }
          });
        }
      },
      initAddRules(disabled = false) {
        let data = this.item ? this.item : {};
        let rules = [{
            title: "身份证照片",
            key: "idCardImg",
            type: "img",
            callback: true,
            skip: true,
            disabled: true,
          },
          {
            title: "患者姓名",
            key: "name",
            value: data.name || "",
            ruleList: ["minLength:2"],
            ruleMsgList: ["患者姓名至少2位"],
            disabled,
          },
          {
            title: "手机号",
            key: "telphone",
            value: data.telphone || "",
            maxlength: 11,
            ruleList: ["isMobile"],
            ruleMsgList: ["请输入正确的手机号码"],
            callback: true,
            disabled,
          },
          {
            title: "验证码",
            key: "smsCode",
            hidden: this.item ? true : false,
            contentWidth: "100px",
          },
          {
            title: "身份证号",
            key: "idCard",
            value: data.idCard || "",
            ruleList: ["isIdCard"],
            ruleMsgList: ["请输入正确的身份证号"],
            callback:true,
            disabled,
          },
          {
            title: "性别",
            key: "sex",
            value: disabled ? (data.sex ? "男" : "女") : 1 - data.sex,
            type: disabled ? "" : "radio",
            selectList: [{
                name: "男",
                value: 1,
              },
              {
                name: "女",
                value: 0,
              },
            ],
            selectKey: "value",
            disabled,
          },
          {
            title: "出生日期",
            key: "birthday",
            value: data.birthday || "",
            type: disabled ? "" : "selectDate",
            disabled,
            callback: true,
          },
          {
            title: "年龄",
            key: "age",
            value: data.age !== "" && data.age !== null && data.age !== undefined ?
              data.age : "",
            disabled: true,
            placeholder: "自动计算，不可编辑",
          },
          {
            title: "民族",
            key: "nation",
            value: disabled ?
              data.nation : data.nation ?
              this.nationList.indexOf(data.nation) : "",
            type: disabled ? "" : "select",
            selectList: this.nationList,
            disabled,
          },
          {
            title: "省市区",
            key: "ssq",
            type: "cascader",
            cascaderProps: {
              children: "childs",
              label: "name",
              value: "name",
            },
            selectList: this.provinces,
            value: data.provinceName ? [data.provinceName, data.cityName, data.areaName] : [],
          },
          {
            title: "详细地址",
            key: "address",
            value: data.address || "",
            type: "textarea",
            disabled,
          },
          {
            title: "身高(cm)",
            key: "height",
            value: Number(data.height) || "",
            disabled,
            ruleList: ["isAmount", "numMin:10"],
            ruleMsgList: ["身高必须是数字最多两位小数", "身高最小为10"],
            callback: true,
            skip: true,
          },
          {
            title: "体重(kg)",
            key: "weight",
            value: Number(data.weight) || "",
            disabled,
            ruleList: ["isAmount", "numMin:10"],
            ruleMsgList: ["体重必须是数字最多两位小数", "体重最小为10"],
            callback: true,
            skip: true,
          },
          {
            title: "BMI",
            key: "bmi",
            value: Number(data.bmi) || "",
            disabled: true,
            placeholder: "自动计算，不可编辑",
            skip: true,
          },
          {
            title: "腰围(cm)",
            key: "waist",
            value: Number(data.waist) || "",
            disabled,
            ruleList: ["isAmount", "numMin:10"],
            ruleMsgList: ["腰围必须是数字最多两位小数", "腰围最小为10"],
            skip: true,
          },
          {
            title: "臀围(cm)",
            key: "hipline",
            value: Number(data.hipline) || "",
            disabled,
            ruleList: ["isAmount", "numMin:10"],
            ruleMsgList: ["臀围必须是数字最多两位小数", "臀围最小为10"],
            skip: true,
          },
          {
            title: "病类",
            key: "diseaseCategory",
            value: disabled ?
              data.diseaseCategory : data.diseaseCategory ?
              this.diseaseList.indexOf(data.diseaseCategory) : "",
            type: disabled ? "" : "select",
            selectList: this.diseaseList,
            disabled,
          },
          {
            title: "确诊日期",
            key: "diagnosisDate",
            value: data.diagnosisDate || "",
            type: disabled ? "" : "selectDate",
            disabled,
          },
          {
            title: "有无血压报告",
            key: "isHaveDynamicReport",
            value: disabled ? (data.isHaveDynamicReport ? "有" : "无") : 1 - data.isHaveDynamicReport,
            type: disabled ? "" : "radio",
            selectList: [{
                name: "有",
                value: 1,
              },
              {
                name: "无",
                value: 0,
              },
            ],
            selectKey: "value",
            disabled,
          },
          {
            type: "actionBtns",
            selectList: [{
                name: "取消",
                value: ""
              },
              {
                name: "提交",
                value: "primary"
              },
            ],
            btnsAligin: "center",
            ruleWidth: "1200px",
            skip:true
          },
        ];
        this.$nextTick(() => {
          this.$refs.basicsAddForm.initForm(rules);
        });
      },
      selectCallback(data) {
        if (data.key == "word") {
          if (data.value) {
            this.$refs.basicsSendForm.changeParamValue({
              key: "content",
              value: data.value
            });
          }
          return
        }
        if (data.key == "deptId") {
          this.hospitalId = data.value;
          this.getDoctors(true);
          this.bloodStandard();
          return
        }
        if (data.key == "idCard") {
          try{
            let birthday = data.value.substring(6, 10) + "-" + data.value.substring(10, 12) + "-" + data.value.substring(12, 14)
            if(this.isValidDate(new Date(birthday))){
              this.$refs.basicsAddForm.changeParamValue({
                key: "birthday",
                value: birthday||''
              });
              this.$refs.basicsAddForm.changeParamValue({
                key: "age",
                value: this.getAgeBirth(birthday)
              });
              this.$refs.basicsAddForm.changeParamValue({
                key: "sex",
                value: 1 - (parseInt(data.value.substr(16, 1)) % 2 === 1?1:0),
              });
            }
          }catch(e){
            //TODO handle the exception
          }
          return
        }
        if (data.key == "idCardImg") {
          let formData = new FormData()
          formData.append('file', data.value.raw)
          discernIdCardOfWeb(formData).then(res => {
            if (res.code == 200) {
              this.changeParamValueByIdCardImg(res.data)
            }
          }).catch(() => {
            this.$refs.basicsAddForm.changeParamValue({
              key: "idCardImg",
              value: "",
            });
          })
          return;
        }
        if (data.key == "telphone") {
          this.telphone = data.value;
          if (this.item) {
            this.$refs.basicsAddForm.changeRulesValue([{
              index: 3,
              key: "hidden",
              value: data.value == this.item.telphone
            }]);
          }
          return;
        }
        if (data.key == "birthday") {
          this.$refs.basicsAddForm.changeParamValue({
            key: "age",
            value: this.getAgeBirth(data.value)
          });
          return;
        }
        if (data.key == "height") {
          this.height = data.value;
        } else if (data.key == "weight") {
          this.weight = data.value;
        }
        let bmi = "";
        if (this.height && this.weight) {
          bmi = Number((Number(this.weight) / Number(this.height) / Number(this.height)) * 10000).toFixed(2);
        }
        this.$refs.basicsAddForm.changeParamValue({
          key: "bmi",
          value: bmi
        });
      },
      changeParamValueByIdCardImg(data) {
        if(data.idCardImg){
          this.$refs.basicsAddForm.changeParamValue({
            key: "idCardImg",
            value: data.idCardImg,
          });
        }
        this.$refs.basicsAddForm.changeParamValue({
          key: "name",
          value: data.name,
        });
        this.$refs.basicsAddForm.changeParamValue({
          key: "idCard",
          value: data.idCard,
        });
        this.$refs.basicsAddForm.changeParamValue({
          key: "age",
          value: data.age,
        });
        this.$refs.basicsAddForm.changeParamValue({
          key: "birthday",
          value: data.birthday,
        });
        this.$refs.basicsAddForm.changeParamValue({
          key: "nation",
          value: this.nationList.indexOf(data.nation),
        });
        this.$refs.basicsAddForm.changeParamValue({
          key: "sex",
          value: 1 - data.sex,
        });
      },
      isValidDate(date) {
        return date instanceof Date && !isNaN(date.getTime())
      },
      getMsg(){
        this.$jsonp("http://localhost:8989/api/ReadMsg").then(res=>{
            if(res.code==0&&res.cardno){
              this.changeParamValueByIdCardImg(
                {
                  name:res.name,
                  idCard:res.cardno,
                  nation:res.nation+'族',
                  sex:res.sex=='男'?1:0
                }
              )
              this.selectCallback({key:'idCard',value:res.cardno})
            }else{
              this.$message.warining('未获取到信息')
            }
         });
      },
      addAction(index) {
        if (index) {
          this.$refs.basicsAddForm.formValid();
        } else {
          this.openView = false;
        }
      },
      addSubmit(param) {
        if (!param) {
          return;
        }
        console.log(param, "addSubmit");
        this.loading = true;
        if (this.item) {
          param.patientId = this.item.patientId;
        }
        param.provinceName = param.ssq[0];
        param.cityName = param.ssq[1];
        param.areaName = param.ssq[2];
        delete param.ssq;
        let param2 = {};
        for (let key in param) {
          if (param[key] !== null && param[key] !== "" && param[key] !== undefined) {
            param2[key] = param[key];
          }
        }
        if (this.item && this.item.telphone == param2.telphone) {
          delete param2.smsCode;
        }
        param2.diseaseCategory = this.diseaseList[param2.diseaseCategory];
        param2.nation = this.nationList[param2.nation];
        let api = this.item ? updatePatientOfWeb : addPatientOfWeb
        api(param2)
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(this.item ? "修改成功" : "新增成功");
              this.codeWaitTime = 60
              if (this.timer) {
                clearInterval(this.timer)
              }
              this.openView = false;
              this.getList();
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //关注，取关
      followChange(patientId, index) {
        followPatientOfWeb({
          patientId
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess(this.tableData[index].isFollow ? "关注成功" : "取关成功");
          }
        }).catch(() => {
          this.tableData[index].isFollow = !this.tableData[index].isFollow
        })
      },
      handleCommand(e, item) {
        if (e == 'xgzl') {
          this.showDetails(item)
        } else if (e == 'bdsb') {
          this.showBind(item)
        } else if (e == 'ghys') {
          this.showChangeDoctor(item)
        }else if (e == 'xyycbz') {
          this.showStandard(item)
        }else if(e == "qywh"){
            this.showkith(item)
        }
      },

      // 亲友维护
      showkith(item){
        this.kithView = true;
        this.item = item;
        this.$nextTick(() => {
          this.$refs.kith.getList(item);
        });
      },
      //更换医生
      showChangeDoctor(item) {
        this.changeDoctorView = true;
        this.item = item;
        this.$nextTick(() => {
          this.getDoctorsByChangeDoctor()
        });
      },
      getDoctorsByChangeDoctor() {
        if (this.doctors) {
          this.initChangeDoctorRules()
        } else {
          doctorAllList({}).then((res) => {
            if (res.code == 200) {
              this.doctors = res.data;
              this.initChangeDoctorRules()
            }
          });
        }
      },
      initChangeDoctorRules() {
        let data = this.item ? this.item : {};
        let rules = [{
            title: "医生",
            key: "doctorId",
            type: "select",
            selectList: this.doctors,
            selectKey: "doctorId",
            selectShowKey: "name",
            value: "",
          },
          {
            title: "更换原因",
            key: "reason",
            value: data.reason || "",
            type: "textarea",
          },
          {
            type: "actionBtns",
            selectList: [{
                name: "取消",
                value: ""
              },
              {
                name: "提交",
                value: "primary"
              },
            ],
            btnsAligin: "center",
            ruleWidth: "1200px",
          },
        ];
        this.$nextTick(() => {
          this.$refs.basicsChangeDoctorForm.initForm(rules);
        });
      },
      changeDoctorAction(index) {
        if (index) {
          this.$refs.basicsChangeDoctorForm.formValid();
        } else {
          this.changeDoctorView = false;
        }
      },
      //提交更换医生
      changeDoctorSubmit(param) {
        if (!param) {
          return;
        }
        console.log(param, "addSubmit");
        this.loading = true;
        param.patientId = this.item.patientId;
        changeDoctorOfWeb(param)
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("提交成功");
              this.changeDoctorView = false;
              this.getList();
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //显示测量数据
      showData(item,flag) {
        this.dataView = true;
        this.item = item;
        this.chartsFlag = true;
        this.activeName = "first";
        this.$nextTick(() => {
          this.$refs.table.init(item.patientId);
          if(flag){
            //切换到趋势图
            this.activeName='second'
            this.tabsClick({index:1})
          }
        });

      },
      //显示待关怀
      showCare(item) {
        if (item.isNeedCare) {
          this.careView = true;
          this.item = item;
          this.$nextTick(() => {
            this.$refs.care.init(item.patientId);
          });
        }
      },
      //显示患者提醒
      showTips(item) {
          this.tipsView = true;
          this.item = item;
          this.$nextTick(() => {
            this.$refs.tips.init(item.patientId);
          });
      },
      //显示绑定设备
      showBind(item) {
        this.bindView = true;
        this.item = item;
        this.$nextTick(() => {
          this.$refs.bind.init(item.patientId);
        });
      },
      tabsClick(tab, event) {
        if (tab.index == 1 && this.chartsFlag) {
          this.chartsFlag = false;
          this.$nextTick(()=>{
            this.$refs.charts.init(this.item.patientId,
            this.item.patientBloodStandard&&this.item.patientBloodStandard.state?this.item.patientBloodStandard:this.standard
            );
          })
        }
      },
      getCode() {
        if (!this.telphone) {
          this.$modal.msgWarning("请输入手机号");
          return
        }
        sendSmsCodeOfWeb({
          phone: this.telphone
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("验证码已发送");
            this.codeWaitTime--
            this.timer = setInterval(() => {
              this.codeWaitTime--
              if (!this.codeWaitTime) {
                clearInterval(this.timer)
                this.codeWaitTime = 60
              }
            }, 1000)
          }
        })
      },
      getAgeBirth(strBirthday) {
        let returnAge;
        const strBirthdayArr = strBirthday.split("-");
        const birthYear = parseInt(strBirthdayArr[0]);
        const birthMonth =parseInt(strBirthdayArr[1]);
        const birthDay = parseInt(strBirthdayArr[2]);

        const d = new Date();
        const nowYear = d.getFullYear();
        const nowMonth = d.getMonth() + 1;
        const nowDay = d.getDate();

        if (nowYear === birthYear) {
          returnAge = 0; // 同年 则为0岁
        } else {
          const ageDiff = nowYear - birthYear; // 年之差
          if (ageDiff > 0) {
            if (nowMonth === birthMonth) {
              const dayDiff = nowDay - birthDay; // 日之差
              if (dayDiff < 0) {
                returnAge = ageDiff - 1;
              } else {
                returnAge = ageDiff;
              }
            } else {
              const monthDiff = nowMonth - birthMonth; // 月之差
              if (monthDiff < 0) {
                returnAge = ageDiff - 1;
              } else {
                returnAge = ageDiff;
              }
            }
          } else {
            returnAge = "0"; // 返回-1 表示出生日期输入错误 晚于今天
          }
        }
        return returnAge; // 返回周岁年龄
      },
      //设备详情
      showSend() {
        this.sendView = true;
        this.$nextTick(() => {
          this.getRemindWordsListOfWeb();
        });
      },
      //常用语
      getRemindWordsListOfWeb() {
        if (this.remind) {
          this.initSendRules()
        } else {
          remindWordsListOfWeb({}).then(res => {
            if (res.code == 200) {
              this.remind = res.data
              this.initSendRules()
            }
          })
        }
      },
      initSendRules() {
        let rules = [{
            title: "常用语",
            key: "word",
            type: "select",
            selectList: this.remind || [],
            selectKey: "dictValue",
            selectShowKey: "dictValue",
            skip: true,
            callback: true,
          },
          {
            title: "内容",
            key: "content",
            type: 'textarea',
          },
          {
            title: "是否通知亲友",
            key: "isSendFamily",
            type: "radio",
            selectList: [{
              name: '否',
              value: 0
            }, {
              name: '是',
              value: 1
            }],
            value: 0,
            skip: true,
          },
          {
            type: "actionBtns",
            selectList: [{
                name: "取消",
                value: ""
              },
              {
                name: "提交",
                value: "primary"
              },
            ],
            btnsAligin: "center",
            ruleWidth: "903px",
          }
        ];
        this.$refs.basicsSendForm.initForm(rules);
      },
      sendAction(index) {
        if (index) {
          this.$refs.basicsSendForm.formValid();
        } else {
          this.sendView = false;
        }
      },
      sendSubmit(param) {
        if (!param) {
          return;
        }
        this.loading = true;
        let patientIds = this.multipleSelection.map(item => {
          return item.patientId
        })
        param.patientIds = patientIds.join(',')
        addRemindBatchOfWeb(param)
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("发送成功");
              this.$refs.multipleTable.clearSelection();
              this.sendView = false;
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //通用血压异常标准
      bloodStandard(flag){
        this.standard={}
        let data={}
        if(this.roleId==2){
          data.deptId=this.hospitalId;
        }
        getBloodStandard(data)
          .then((res) => {
            if (res.code == 200&&res.data.length) {
              this.standard= res.data[0];
            }
          })
      },
      showStandard(item){
        if(item.patientBloodStandard&&item.patientBloodStandard.pbId){
          this.item=item.patientBloodStandard
        }else{
          this.item=this.standard
        }
         this.item.patientId=item.patientId
          this.standardView = true;
          this.$nextTick(() => {
            this.initStandardRules();
          });
      },
      initStandardRules() {
        let item = this.item ? this.item : {};

        let rules = [
          {
            title: "收缩压基准线",
            key: "sbpNum",
            value: item.sbpNum || "",
            ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            ruleMsgList: ['收缩压基准线必须是纯数字无小数', '收缩压基准线最小为1', '收缩压基准线最大为1000']
          },
          {
            title: "收缩压偏高提醒(0%<偏高<=n%)",
            key: "sbpLevel1",
            value: item.sbpLevel1 || "",
            ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            ruleMsgList: ['收缩压偏高提醒必须是纯数字无小数', '收缩压偏高提醒最小为1', '收缩压偏高提醒最大为1000']
          },
          {
            title: "收缩压中度提醒(偏高%<中度<=n%)",
            key: "sbpLevel2",
            value: item.sbpLevel2 || "",
            ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            ruleMsgList: ['收缩压中度提醒必须是纯数字无小数', '收缩压中度提醒最小为1', '收缩压中度提醒最大为1000'],
          },
          {
            title: "收缩压严重提醒：> 中度%",
            type:'title',
            hiddenBottom:true,
            ruleWidth: "503px",
            // value: item.sbpLevel3 || "",
            // ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            // ruleMsgList: ['收缩压严重提醒必须是纯数字无小数', '收缩压严重提醒最小为1', '收缩压严重提醒最大为1000'],
          },
          {
            title: "舒张压基准线",
            key: "dbpNum",
            value: item.dbpNum || "",
            type: 'number',
            ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            ruleMsgList: ['舒张压基准线必须是纯数字无小数', '舒张压基准线最小为1', '舒张压基准线最大为1000']
          },
          {
            title: "舒张压偏高提醒(0%<偏高<=n%)",
            key: "dbpLevel1",
            value: item.dbpLevel1 || "",
            ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            ruleMsgList: ['舒张压偏高提醒必须是纯数字无小数', '舒张压偏高提醒最小为1', '舒张压偏高提醒最大为1000'],
          },
          {
             title: "舒张压中度提醒(偏高%<中度<=n%)",
            key: "dbpLevel2",
            value: item.dbpLevel2 || "",
            ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
            ruleMsgList: ['舒张压中度提醒必须是纯数字无小数', '舒张压中度提醒最小为1', '舒张压中度提醒最大为1000'],
          },
          {
           title: "舒张压严重提醒：> 中度%",
           type:'title',
           hiddenBottom:true,
           ruleWidth:'503px',
           // title: "舒张压严重提醒(%)",
           // key: "dbpLevel3",
           // value: item.dbpLevel3 || "",
           // ruleList: ['isNum', 'numMin:1', 'numMax:1000'],
           // ruleMsgList: ['舒张压严重提醒必须是纯数字无小数', '舒张压严重提醒最小为1', '舒张压严重提醒最大为1000'],
          },
          {
            title: "是否启用",
            key: "state",
            type:'radio',
            value: item.state?0:1,
            selectKey:'value',
            selectList:[{name:'是',value:1},{name:'否',value:0}]
          },
          {
            type: "actionBtns",
            selectList: [{
                name: "取消",
                value: ""
              },
              {
                name: "提交",
                value: "primary"
              },
            ],
            btnsAligin: "center",
            ruleWidth: "503px",
          },
        ];
        this.$refs.basicsStandardForm.initForm(rules);
      },
      //自定义表单校验
      customValid(data) {
        let errorTip = "";
        if (
           data.sbpLevel2 <=data.sbpLevel1
        ) {
          errorTip = "收缩压中度提醒必须大于收缩压偏高提醒";
        }else if (data.dbpLevel2 <=data.dbpLevel1
        ) {
          errorTip = "舒张压中度提醒必须大于舒张压偏高提醒";
        }
        if (errorTip) {
         this.$modal.msgWarning(errorTip);
          return false
        } else {
         return true
        }
      },
      standardAction(index) {
        if (index) {
          this.$refs.basicsStandardForm.formValid();
        } else {
          this.standardView = false;
        }
      },
      standardSubmit(param) {
        if (!param) {
          return;
        }
        let flag= this.customValid(param)
        if(!flag){
          return
        }
        this.loading = true;
        for (let key in param) {
          this.item[key] = param[key]
        }
        saveBloodStandard(this.item)
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.standardView = false;
              this.getList();
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //删除
      del(patientId) {
        this.loading = true;
        this.tableLoading = true;
        removePatient({ patientId })
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("删除成功");
              this.getList();
            }
          })
          .finally(() => {
            this.loading = false;
            this.tableLoading = false;
          });
      },
      initImport(){
         let rules = [
            {
              title: "文件",
              key: "file",
              type: "file",
              uploadAction:
                process.env.VUE_APP_BASE_API +
                "/chronicdisease/hospital/importPatient",
              submitInUpload: true,
            },
            {
              type: "actionBtns",
              selectList: [
                { name: "取消", value: "" },
                { name: "提交", value: "primary" },
              ],
              btnsAligin: "center",
              ruleWidth: "503px",
            }
          ];
          console.log(rules,'========================');
          this.$refs.batchImportForm.initForm(rules);
      },
      batchImportAction(index){
        if (index) {
          this.$refs.batchImportForm.formValid();
        } else {
          this.batchImportOpen = false;
        }
      },
      batchImportSubmit(param) {
        if (!param) {
          return;
        }
        this.$modal.msgSuccess("导入成功");
        this.batchImportOpen = false;
        this.getList();
      },
      down(){
        this.download('/chronicdisease/hospital/downloadPatientTemplate', {
              }, `患者模板.xlsx`)
      }
    },
  };
</script>
<style scoped lang="scss">
  .test-wrap{
    display: flex;
    flex-wrap: wrap;
    div{
      width: 50%;
    }
  }
</style>
